﻿CREATE TRIGGER [dbo].[tr_Loan_Dealer]
ON [dbo].[t_Loan] 
FOR UPDATE
AS

IF UPDATE (ContractHolderID) BEGIN
	DECLARE @DSPID int
	SELECT @DSPID = D_SP.ID FROM  t_ContractHolder AS CH
	INNER JOIN t_Dealer_SalesPersons AS D_SP ON CH.DealerID = D_SP.DealerID
	WHERE (CH.ID = dbo.IsContractHolder())

	IF ISNULL(@DSPID,0)>0
		UPDATE t_Loan SET DealerSalesPersonID = @DSPID
		FROM t_Loan INNER JOIN inserted ON t_Loan.ID = inserted.ID
END

IF UPDATE (DealerSalesPersonID) BEGIN

BEGIN TRAN

UPDATE t_TrackerRequest SET DealerID = dsp.DealerID
FROM t_TrackerRequest TR
INNER JOIN v_TrackerRequest vtr ON vtr.TrackerRequestID = TR.ID
INNER JOIN t_CarInfo ci ON ci.VIN = TR.VIN
INNER JOIN inserted l ON l.ID = ci.LoanID
INNER JOIN t_Dealer_SalesPersons dsp ON dsp.ID = l.DealerSalesPersonID
WHERE vtr.IsActive = 1 AND TR.DealerID <> dsp.DealerID

IF @@ERROR <> 0 BEGIN ROLLBACK TRAN RETURN END

--UPDATE L SET BreakdownCode = NULL
--FROM t_Loan L INNER JOIN inserted i ON L.ID = i.ID
--INNER JOIN 

IF @@ERROR <> 0 ROLLBACK TRAN ELSE COMMIT TRAN
END
